import { getCampusSelector } from '@/api/campus/campus'
import request from '@/utils/request'
import CustomEditForm from './EditForm/index.vue'
import ExportBox from './ExportBox'
import CustomForm from './Form/index.vue'
import CustomViewForm from './ImageView/index.vue'
export default {
  components: { CustomForm, ExportBox, CustomEditForm, CustomViewForm },
  data() {
    return {
      name: 'campus.decoration',
      showAll: false,
      query: {
        campusId: undefined,
        type: undefined,
        acceptTime: undefined,
        brand: undefined
      },
      list: [],
      listLoading: true,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: ''
      },
      formVisible: false,
      formEditVisible: false,
      formViewVisible: false,
      exportBoxVisible: false,
      recordsVisible: false,
      columnList: [{ prop: 'brand', label: '校区品牌' }, { prop: 'campusCode', label: '校区编码' }, { prop: 'province', label: '省份' }, { prop: 'city', label: '城市' }, { prop: 'campusName', label: '校区简称' }, { prop: 'type', label: '沟通类型' }, { prop: 'subject', label: '沟通主题' }, { prop: 'statusText', label: '处理状态' }, { prop: 'sourceText', label: '沟通来源' }, { prop: 'contacts', label: '联系人' }, { prop: 'mobile', label: '联系电话' }, { prop: 'description', label: '描述' }, { prop: 'acceptTime', label: '受理时间' }, { prop: 'assigned', label: '分配给' }],
      campusOptions: [],
      campusLoading: false,
      typeOptions: [],
      brandOptions: [],
      statusOptions: [{ fullName: '处理中', id: '1' }, { fullName: '已处理', id: '2' }, { fullName: '特殊处理', id: '3' }, , { fullName: '已完结', id: '4' }],
      sourceOptions: [{ fullName: '400', id: 1 }, { fullName: '家校平台', id: 2 }, { fullName: '贝尔校长云', id: 3 }, { fullName: 'VIP群反馈', id: 4 }],
      dialogFormVisible: false,
      form: {
        id: '',
        status: ''
      },
      formLabelWidth: '120px',
      rules: {
        status: [
          {
            required: true,
            message: '请选择审核意见',
            trigger: 'change'
          }
        ]
      }
    }
  },
  computed: {},
  created() {
    this.initData()
    this.loadCampusOptions()

    this.$store.dispatch('base/getDictionaryData', { sort: 'ConnectType' }).then(res => {
      this.typeOptions = res
    })
    this.$store.dispatch('base/getDictionaryData', { sort: 'Brand' }).then(res => {
      this.brandOptions = res
    })
  },
  methods: {
    /**
     * 加载校区下拉框选项
     * 说明：统一使用 getCampusSelector 接口获取校区列表，
     * 下拉显示格式为 “校区全称(校区编码)”，并在页面加载时预先获取；
     * 同时暴露校园加载状态 campusLoading 以供 UI 显示加载反馈。
     */
    async loadCampusOptions() {
      try {
        this.campusLoading = true
        const res = await getCampusSelector({ bran: this.query.brand, fields: 'id,fullName' })
        this.campusOptions = Array.isArray(res.data) ? res.data : []
      } catch (error) {
        console.error('加载校区数据失败:', error)
        this.$message.error('加载校区数据失败')
      } finally {
        this.campusLoading = false
      }
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == 'ascending' ? 'asc' : 'desc'
      this.listQuery.sidx = !order ? '' : prop
      this.initData()
    },
    initData() {
      this.listLoading = true
      let _query = {
        ...this.listQuery,
        ...this.query
      }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      request({
        url: `/api/campus/decoration`,
        method: 'GET',
        data: query
      }).then(res => {
        let pageList = res.data.list.map(item => {
          return {
            ...item,
            ...{ floorPlanArray: item.floorPlan ? JSON.parse(item.floorPlan) : {} }
          }
        })
        this.list = pageList
        this.total = res.data.pagination.total
        this.listLoading = false
      })
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          request({
            url: `/api/campus/decoration/${id}`,
            method: 'DELETE'
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    AuditingHandle(id) {
      this.form.id = id
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields()
      })
    },
    onSubmitAuditing() {
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          this.$confirm('是否' + (this.form.status == 1 ? '退回' : '通过') + '该条投诉建议, 是否继续?', '提示', {
            type: 'warning'
          }).then(() => {
            request({
              url: `/api/campus/connect/${this.form.id}/${this.form.status}`,
              method: 'post'
            }).then(res => {
              this.$message({
                type: 'success',
                message: res.msg,
                onClose: () => {
                  this.dialogFormVisible = false
                  this.initData()
                }
              })
            })
          })
        }
      })
    },
    closedHandle(id) {
      this.$confirm('此操作将关闭该建议投诉, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          request({
            url: `/api/campus/connect/close/${id}`,
            method: 'post'
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    handleSelectionChange(val) {
      const res = val.map(item => item.id)
      this.multipleSelection = res
    },
    viewOrUpdateHandle(file) {
      this.formViewVisible = true
      this.$nextTick(() => {
        this.$refs.CustomViewForm.init(file.url, file.name)
      })
    },
    editOrUpdateHandle(id, isDetail, row) {
      this.formEditVisible = true
      this.$nextTick(() => {
        this.$refs.CustomEditForm.init(id, isDetail, row)
      })
    },
    addOrUpdateHandle(id, isDetail, row) {
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.CustomForm.init(id, isDetail, row)
      })
    },

    exportData() {
      this.exportBoxVisible = true
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.columnList)
      })
    },
    download(data) {
      let query = { ...data, ...this.listQuery, ...this.query }
      request({
        url: `/api/campus/connect/Actions/Export`,
        method: 'GET',
        data: query
      }).then(res => {
        if (!res.data.url) return
        window.location.href = this.define.comUrl + res.data.url
        this.$refs.ExportBox.visible = false
        this.exportBoxVisible = false
      })
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: ''
      }
      this.initData()
    },
    refresh(isrRefresh) {
      this.formVisible = false
      if (isrRefresh) this.reset()
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: ''
      }
      this.initData()
    }
  }
}
